package com.tanhua.sso.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserInfoService {
    @Value("${jwt.secret}")
    private String secret;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private FaceEngineService faceEngineService;

    /**
     * 保存用户的信息
     *
     * @param param
     * @param token
     * @return
     */
    public Boolean loginReginfo(Map<String, String> param, String token) {
        try {
            //1.token校验
            User user = this.checkToken(token);
            if (user == null) {
                return false;
            }
            //2.封装用户信息
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(user.getId());
            userInfo.setSex(StringUtils.equalsIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
            userInfo.setNickName(param.get("nickname"));
            userInfo.setBirthday(param.get("birthday"));
            userInfo.setCity(param.get("city"));
            userInfoMapper.insert(userInfo);
            return true;
        } catch (Exception e) {
            log.error("UserInfoService保存用户信息失败!");
            return false;
        }
    }

    /**
     * 对token信息进行校验
     *
     * @param token
     * @return
     */
    public User checkToken(String token) {
        try {
            //解析token
            Map<String, Object> mapBody = Jwts.parser().setSigningKey(secret)
                    .parseClaimsJws(token).getBody();
            //2.封装解析的token的用户信息
            User user = new User();
            user.setId(Long.valueOf(mapBody.get("id").toString()));
            //3.查找redis缓存中是否有手机号
            String redisKey = "INSERT_USER_MOBILE" + user.getId();
            if (redisTemplate.hasKey(redisKey)) {
                String mobile = redisTemplate.opsForValue().get(redisKey);
                user.setMobile(mobile);
            } else {
                //查找用户手机号
                User userMobile = userMapper.selectById(user.getId());
                user.setMobile(userMobile.getMobile());
                //3.写入到redis缓存中
                long timeOut = Long.valueOf(mapBody.get("exp").toString()) * 1000 - System.currentTimeMillis();
                redisTemplate.opsForValue().set(redisKey, userMobile.getMobile(), timeOut, TimeUnit.MILLISECONDS);
            }
            return user;
        } catch (Exception e) {
            //解析token异常
            log.error("解析token异常!");
            return null;
        }
    }

    /***
     * 上传图像
     * @param file
     * @param token
     * @return
     * @throws IOException
     */
    public PicUploadResult uploadLogo(MultipartFile file, String token) throws IOException {
        //1.校验token
        User user = checkToken(token);
        if (user == null) {
            log.error("token校验失败!");
            return null;
        }
        //校验图像是否是人像
        boolean flag = faceEngineService.checkIsPortrait(file.getBytes());
        if (!flag) {
            return null;
        }
        //利用第三方==>阿里云OSS存储文件
        PicUploadResult upload = picUploadService.upload(file);
        if (StringUtils.isEmpty(upload.getName())) {
            return null;
        }
        //上传成功,保存图像到用户信息中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(upload.getName());
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        int result = userInfoMapper.update(userInfo, queryWrapper);
        return result == 1 ? upload : null;
    }


    /**
     * 保存手机号码
     * @param userId
     * @param newPhone
     * @return
     */
    public Boolean updatePhone(Long userId, String newPhone) {
        //先查询新手机号是否已经注册，如果已经注册，就不能修改
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", newPhone);
        User user = this.userMapper.selectOne(queryWrapper);
        if(ObjectUtil.isNotEmpty(user)){
            //新手机号已经被注册
            return false;
        }

        user = new User();
        user.setId(userId);
        user.setMobile(newPhone);

        return this.userMapper.updateById(user) > 0;
    }
}
